package com.legrand.www.module.core.role;

import com.legrand.www.module.core.annotation.RolePermission;
import com.legrand.www.module.exception.exception.CustomizeException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiah
 * 2018-06-22 03:42:45
 * 使用切面对权限做更加细粒度的控制，只有相应角色的用户才能调用一下接口，该接口部分地址不对，需要修改
 */
@Aspect
@Component
public class RoleAopControl {
    @Pointcut(value = "@annotation(com.legrand.www.module.core.annotation.RolePermission)")
    public void controller() {

    }

    @Around("controller()")
    public Object rightControl(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        if (targetMethod.isAnnotationPresent(RolePermission.class)) {
            //获取方法上注解中表明的权限
            RolePermission permission = targetMethod.getAnnotation(RolePermission.class);
            String[] roles = permission.roles();
            List<String> roleList = new ArrayList<>();
            for (String ss : roles) {
                roleList.add(ss);
            }
            //获取当前用户拥有的权限
            //User user = RequestUtil.getUser();
                     /*if ( user == null ) {
                            throw new Exception("User is null");
                     }
                     List<String> userRoles = user.getUserRoles();*/
            List<String> userRoles = new ArrayList<>();
            userRoles.add("user");
            for (String role : userRoles) {
                if (roleList.contains(role)) {
                    //如果当前用户拥有的权限包含方法注解上的权限,则执行被拦截到的方法
                    return pjp.proceed();
                }
            }
            //如果没有权限,抛出异常,由Spring框架捕获,跳转到错误页面
            throw new CustomizeException("403","The role have no right to use the API");
        }
        //*普通方法无需权限控制*//*
        return pjp.proceed();
    }
}
